//
//  HPComposedView.swift
//  MyWeibo
//
//  Created by apple on 16/4/19.
//  Copyright © 2016年 Apengpeng. All rights reserved.
//

import UIKit
import SnapKit

class HPComposedView: UIView {
    var target: UIViewController?
    
    // 给外界提供一个方法, 
    func show(target: UIViewController) {
        
        self.target = target
        target.view.addSubview(self)
    }
    
    override init(frame: CGRect) {
        let rect = UIScreen.mainScreen().bounds
        super.init(frame: rect)
        
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setupUI() {
        
        addSubview(backImage)
        addSubview(sloganImage)
        
        backImage.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.snp_edges)
        }
        
        sloganImage.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top).offset(100)
            make.centerX.equalTo(self.snp_centerX)
        }
        addChildBtn()
    }
    
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        for (indx, btn) in btnArray.reverse().enumerate() {
           setAnimationForButton(false, btn: btn, indx: indx)
        }
    }
    
//    override func willMoveToSuperview(newSuperview: UIView?) {
//        super.willMoveToSuperview(newSuperview)
//        for btn in btnArray {
//            
//            UIView.animateWithDuration(3.0, delay: 2, usingSpringWithDamping: 5, initialSpringVelocity: 4, options: [], animations: { () -> Void in
//                btn.center.y = btn.center.y - 300
//                }, completion: { (_) -> Void in
//                    print("动画执行了")
//            })
//        }
//
//    }

    override func willMoveToWindow(newWindow: UIWindow?) {
        super.willMoveToWindow(newWindow)
        for (indx, btn) in btnArray.enumerate() {
            
            setAnimationForButton(true, btn: btn, indx: indx)
        }
    }
    
    private func setAnimationForButton(isUp: Bool = true, btn: HPComposedBtn, indx: Int) {
        
            UIView.animateWithDuration(0.8, delay: Double(indx) * 0.2, usingSpringWithDamping: 6, initialSpringVelocity: 2, options: [], animations: { () -> Void in
                btn.center.y = btn.center.y + (isUp ? -screenHeight / 2 : screenHeight)
                
                }, completion: { (_) -> Void in
                    if !isUp {
                        self.removeFromSuperview()
                    }
                    print("按钮动画")
            })
    }
    
    
//    override func willRemoveSubview(subview: UIView) {
//        
//        for (indx, btn) in btnArray.reverse().enumerate() {
//            UIView.animateWithDuration(0.8, delay: Double(indx) * 0.2, usingSpringWithDamping: 5, initialSpringVelocity: 4, options: [], animations: { () -> Void in
//                btn.center.y = btn.center.y + screenHeight
//                }, completion: { (_) -> Void in
//                    super.willRemoveSubview(subview)
//                    print("removeSubView")
//            })
//        }
//    }

    
    private lazy var btnArray: [HPComposedBtn] = [HPComposedBtn]()
    
    // 磨砂效果初始化
//    private lazy var backImage: UIImageView = UIImageView(image: UIImage.shortScreenPicture().applyLightEffect())
//    private lazy var backImage: UIImageView = UIImageView(image: UIImage.shortScreenPicture().applyDarkEffect())
    //    private lazy var backImage: UIImageView = UIImageView(image: UIImage.shortScreenPicture().applyExtraLightEffect())
    private lazy var backImage: UIImageView = UIImageView(image: UIImage.shortScreenPicture().applyTintEffectWithColor(UIColor.yellowColor()))
    
    private lazy var sloganImage: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
    // 懒加载数据
    private lazy var composedItem: [HPComposed] = {

        let path = NSBundle.mainBundle().pathForResource("Compose.plist", ofType: nil)!
        let array = NSArray(contentsOfFile: path) as! [[String:String]]
        
        var itemArray = [HPComposed]()
        // 遍历字典
        for item in array {
            let composedItem = HPComposed(dict: item)
            itemArray.append(composedItem)
        }
        
        return itemArray
    }()
}



// 添加按钮
extension HPComposedView {
    
    private func addChildBtn() {
        let count:CGFloat = 3
        let totalCount = composedItem.count
        let btnW: CGFloat = 80
        let btnH: CGFloat = 110
        let btnMargin = (screenWidth - btnW * count) / (count + 1)
        let rect = CGRect(x: 0, y: 0, width: btnW, height: btnH)
        for i in 0..<totalCount {
            let item = composedItem[i]
            let btn = HPComposedBtn()
            btn.composedItem = item
            btn.titleLabel?.textAlignment = .Center
            btn.setTitleColor(UIColor.darkGrayColor(), forState: .Normal)
            
            let row = i / 3
            let col = i % 3
            let dx = (btnW + btnMargin) * CGFloat(col) + btnMargin
            let dy = (btnH + btnMargin) * CGFloat(row) + screenHeight
            btn.frame = CGRectOffset(rect, dx, dy)
            
            btn.addTarget(self, action: "btnDidClick:", forControlEvents: .TouchUpInside)
            
            addSubview(btn)
            
            btnArray.append(btn)
        }
    }
    
    //MARK:按钮点击
    @objc private func btnDidClick(button: HPComposedBtn) {
        for btn in btnArray {
            var scale: CGFloat = 0
            
            if btn == button {
                scale = 1.5
            } else {
                scale = 0.5
            }
            
            UIView.animateWithDuration(0.4, animations: { () -> Void in
                btn.alpha = 0
                btn.transform = CGAffineTransformMakeScale(scale, scale)
                }, completion: { (_) -> Void in
                    self.removeFromSuperview()
                    print("按钮消失了")
            })

        }
        
        guard let className = button.composedItem?.target else {
            print("target中的值为空")
            return
        }
        
        // 获取类型
        let classType = NSClassFromString(className) as! UIViewController.Type
        //            let classType = NSClassFromString(className) as! UIViewController.Type
        // 创建控制器
        let composeVC = classType.init()
        let nav = UINavigationController(rootViewController: composeVC)
        
        // 添加控制器
        target?.presentViewController(nav, animated: true, completion: { () -> Void in
            // 移除控制器
            self.removeFromSuperview()
        })
    }
}

